package kin.system.util;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import javax.inject.Inject;

import org.springframework.web.context.WebApplicationContext;

import com.opensymphony.xwork2.interceptor.I18nInterceptor;

import kin.bean.security.Button;
import kin.bean.system.Form;
import kin.bean.system.KinColumn;
import kin.bean.system.KinForm;
import kin.bean.system.M2M;
import kin.bean.system.M2O;
import kin.bean.system.O2M;
import kin.bean.system.O2O;
import kin.bean.system.Xtype;
import kin.dao.system.XtypeManagerIMP;
import kin.manager.system.FormManager;
import kin.manager.system.XtypeManager;
import kin.proxy.I18nProxy;
import kin.service.security.ButtonServiceManager;
import kin.service.system.FormServiceManager;
import kin.serviceIMP.security.ButtonServiceManagerIMP;
import kin.test.Iii;

public class JsonBuildClassAttribute {
	
	
	
	public static String getExcelField(Form form ){
		StringBuilder result = new StringBuilder();
	/*	for (KinColumn c : form.getKinColumns()) {
			if (!c.isSerializable() || !c.isHidden())
				hm.put(className + "-" + c.getFieldName(), c.getHeader());
		}

		for (M2O m2o : form.getM2os()) {
			hm.put(className + "-" + m2o.getName() + "-" + m2o.getComboName(),m2o.getLabel());
		}*/

		return result.toString();
	}
	
	
	public static String getModel(Form form) {
		StringBuilder result = new StringBuilder();
		StringBuilder fields = new StringBuilder();
		StringBuilder m2os = new StringBuilder();
		StringBuilder o2os = new StringBuilder();
		StringBuilder o2ms=new StringBuilder();
		
		
		result.append("[");

		for (KinColumn c : form.getKinColumns()) {
			fields.append("{");
			fields.append("name:'" + c.getFieldName() + "',type:'"+c.getType().toLowerCase()+"'");
          if(c.getType().equals("date")){
        	  
        	   fields.append(",dateFormat: 'Y-m-d'");
           }
			
			fields.append("},");

		}
	 

		for (M2O m2o : form.getM2os()) {
		if(m2o.isRenderToBuildForm()){
			m2os.append("{");
			m2os.append("name:'" + m2o.getName() + "'");
			
			m2os.append("},");
		}
			
		}
		
		for(O2O o2o:form.getO2os()){
			if(o2o.isRenderToBuildForm()){
				o2os.append("{");
				o2os.append("name:'" + o2o.getName()  + "'");
				
				o2os.append("},");
			}
		}
		
		
		for(O2M o2m:form.getO2ms()){
			if(o2m.isRenderToBuildForm()){
				o2ms.append("{");
				o2ms.append("name:'"+o2m.getName()+"'");
				o2ms.append("},");
			}
		}
		
		result.append(fields);
		result.append(o2os);
		result.append(m2os);
		result.deleteCharAt(result.length() - 1);
		result.append("]");
		
		System.out.println("Model----------------" + result);
		return result.toString();
	}
	
	
	public static String getButtons(Form form){
		
		StringBuilder buttons=new StringBuilder();
		
		ButtonServiceManager buttonServiceManager=(ButtonServiceManager) ApplicationContextHelper.getBean("buttonServiceManagerIMP");
		
			LinkedHashMap<String,Object> bw=new LinkedHashMap<String,Object>();
			bw.put("targetName", StringUtil.fristLetterLowerCase(form.getForm_name()));
			bw.put("renderToList",true);
			List<Button> bs = null;
			try {
				 bs=buttonServiceManager.findList(bw, null, null,null);
			} catch (Exception e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
			if(bs!=null){
				buttons.append("[");
			for(Button b:bs){
				buttons.append("{xtype : 'button',text:'"+b.getLabel()+"',action:'"+b.getAction()+"',actionUrl:'"+b.getUrl()+"',"+"targetName:'"+b.getTargetName()+"',method:'"+b.getMethod()+"'");
			    if(b.getAction().equals("delete")||b.getAction().equals("update")){
			    	buttons.append(",disabled:true");
			    }
				buttons.append("},");
				String sssss=ApplicationContextHelper.getApplicationContext().getMessage(b.getLabel(), null, Locale.CHINA);
				
			}
			StringUtil.deleteLastSymbol(buttons, ",");
			buttons.append("]");
			}
			
		return buttons.toString();
		
	}
	
	
	public static String getForm(Form form,int id) {
		XtypeManager target=new XtypeManagerIMP();
		InvocationHandler ds = new I18nProxy(target.getClass());
		XtypeManager xtypeManager=(XtypeManager) Proxy.newProxyInstance(XtypeManager.class.getClassLoader(), new Class[]{XtypeManager.class},ds);
		
		ButtonServiceManager bsm=(ButtonServiceManager) ApplicationContextHelper.getBean("buttonServiceManagerIMP");
		
		
		
		List<Button> bs = null;
		
		
	
		StringBuilder result = new StringBuilder();
		StringBuilder prop = new StringBuilder();
		StringBuilder o2m_list=new StringBuilder();
		StringBuilder o2ms = new StringBuilder();
		
		StringBuilder o2os = new StringBuilder();
		
		StringBuilder buttons=new StringBuilder();
		if(bs!=null){
			buttons.append("buttons:[");
		for(Button b:bs){
			buttons.append("{xtype : 'button',text:'"+b.getLabel()+"',action:'"+b.getAction()+"'");
		
			buttons.append("},");
		}
		buttons.append("]");
		}
		Object me= ApplicationContextHelper.getBean(StringUtil.fristLetterLowerCase(form.getForm_name()) + "ServiceManagerIMP");
	   Object hh=null;
		try {
			hh = me.getClass().getMethod("get",new Class[] { Serializable.class }).invoke(me, id);
		} catch (IllegalArgumentException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SecurityException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (InvocationTargetException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (NoSuchMethodException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		result.append("{");
		//System.out.println("form.getColumns():" + form.getColumns().size());

		prop.append("prop:");
		prop.append("[");
		for (KinForm c : form.getKinForms()) {
			Xtype xtype=Xtype.valueOf(c.getXtype());
			
         switch(xtype){
       case combo:  prop.append(xtypeManager.combo(c.getLabel(),c.getFieldName(),c.isAllowBlank(),c.getSort(),false,false, true, StringUtil.fristLetterUpperCase(c.getFieldName()),null, null, null, null));
      // prop.append(XtypeFactory.combo(c.getLabel(),c.isAllowBlank(),c.getSort(),false,false,c.getFieldName(), true, StringUtil.fristLetterUpperCase(c.getFieldName()),null, null, null, null));
         prop.append(",");
         break;
         case textfield:prop.append(xtypeManager.textfield(c.getLabel(),c.getFieldName(), c.getMinLength(),c.getMaxLength(),c.isAllowBlank(),c.getVtype(),c.getSort(),c.isHidden()));
         prop.append(",");
         break;
         case numberfield:prop.append(xtypeManager.numberfield(c.getLabel(), c.getFieldName(),c.isAllowBlank(),c.getMin(),c.getMax(),c.getSort(), c.isHidden()));
         prop.append(",");
         break;
         case datefield:prop.append(xtypeManager.datefield( c.getLabel(),c.getFieldName(),c.isAllowBlank(),c.getSort(),"Y-m-d",c.isHidden(),false));
         prop.append(",");
         break;
         case checkbox:
	        	//field.append(",editor:");
        	 prop.append(xtypeManager.checkbox(c.getLabel(),c.getFieldName(),c.getSort(), c.isHidden()));
        	 prop.append(",");
	        	break;
         case ckeditorfield:
	        	//field.append(",editor:");
     	 prop.append(xtypeManager.ckeditorfield(c.getLabel(),c.getFieldName(),c.isAllowBlank(),c.getSort()));
     	 prop.append(",");
	        	break;
	        	  	
	        	
         }
			/*prop.append("{");
			prop.append("fieldLabel:'" + c.getHrader() + "',");
			prop.append("name:'" + c.getColumns_name() + "'");
			prop.append(",xtype:'" + c.getXtype() + "'");
			if(c.getType().equals("date")){
				prop.append(", format:'Y-m-d'");
				prop.append(", renderer:function(value){return value ? Ext.Date.dateFormat(value,'Y-m-d'):'';}");
				//field.append(",renderer:function(value, id, r) {console.dir(r); var d = new Date(r.data['"+c.getColumns_name()+"']);return d.format('Y/m/d');}");
}}*/
         }
		System.out.println(prop);
		
	
		for (M2O m : form.getM2os()) {
          if( m.isRenderToBuildForm()){
        	  if("treecombo".equals(m.getXtype())){
        		  prop.append(xtypeManager.treecombo(m.getLabel(),m.getName(),true,m.getComboName(),m.getTargetEntity()));
        	  }else{
			prop.append(xtypeManager.combo(m.getLabel(),m.getName(),m.isAllowBlank(),m.getSort(),false, false , false, m.getTargetEntity(),m.getComboName(), null, null, null));
        	  }
			prop.append(",");
          }
		}
		
		
		for (M2M m2m : form.getM2ms()) {
			Object tag = ApplicationContextHelper.getBean(StringUtil.fristLetterLowerCase(m2m.getTargetEntity()) + "ServiceManagerIMP");
		    

			
			
			prop.append("{" + "xtype: 'checkboxgroup'," + "fieldLabel :'"
					+ StringUtil.fristLetterLowerCase(m2m.getTargetEntity())
					+ "',"
					// + "cls: 'x-check-group-alt',"
					// Distribute controls across 3 even columns, filling each
					// row
					// from left to right before starting the next row
					+ "columns: 6," + "items: [");
			try {
				Method method = tag.getClass().getMethod("findAll",
						new Class[] {});
				List l = (List) method.invoke(tag, null);

				for (int i = 0; i < l.size(); i++) {
					Object obj = l.get(i);
					Method name = obj.getClass().getMethod(
							"get" + m2m.getTargetEntity() + "_name",
							new Class[] {});
					String s_name = (String) name.invoke(obj, null);
					Method getId = obj.getClass().getMethod(
							"get" + m2m.getTargetEntity() + "_id",
							new Class[] {});
					int s_id = (Integer) getId.invoke(obj, null);
					
					/*Method set = me.getClass().getMethod("get",
							new Class[] { Serializable.class });*/
					
					
					boolean isCheck = false;
					// System.out.println("dddffff:"+hh.getClass().getMethod("get"+form.getForm_name()+"_name",
					// new Class[]{}).invoke(hh, null));
					if(hh!=null){
						Set ll = (Set) hh.getClass().getMethod("get" + m2m.getTargetEntity() + "s",new Class[] {}).invoke(hh, null);

						Iterator ite = ll.iterator();// 灏唄s杞崲涓轰竴涓彲閬嶅巻鐨勫璞terator
						while (ite.hasNext()) {
							Object oob = ite.next();
							int u_id = (Integer) oob.getClass().getMethod("get" + m2m.getTargetEntity()+ "_id",new Class[]{}).invoke(oob, null);
							if (s_id == u_id) {
								isCheck = true;
							}
						}
					}
					prop.append("{boxLabel: '" + s_name + "', inputValue: " + s_id
							+ ", checked:" + isCheck + ",name:'"+StringUtil.fristLetterLowerCase(m2m.getTargetEntity()) + "s'},");
				}
				
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            
			prop.append("]}");
		}
		if(prop.length()-1==prop.lastIndexOf(",")){
			prop.deleteCharAt(prop.length()-1);
		}
		prop.append("],");
		// -------------------------------------------------
		
		o2m_list.append("o2m_list:[");
		o2ms.append("o2ms:[");
		
		for (O2M o2m : form.getO2ms()) {
			if(o2m.isRenderToBuildForm()){
			//System.out.println("O2M calss:"+o2m.getTargetEntity());
				LinkedHashMap<String, Object> where=new LinkedHashMap<String, Object>();
	        	where.put("form_name", o2m.getTargetEntity());
	        	
	        	FormServiceManager mr=	(FormServiceManager) ApplicationContextHelper.getBean("formServiceManagerIMP");
	        	Form subform = null;
				try {
					subform = (Form)mr.find( where, null,null);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				if("list".equals(o2m.getXtype())){
					o2m_list.append("'"+o2m.getName()+"'"+",");
				}
				StringUtil.deleteLastSymbol(o2m_list, ",");
				/*if(subform==null){
			o2ms.append("{xtype:'"+o2m.getXtype()+"',title:'"+o2m.getTitle()+"',pid:"+id+",columns:columnsFactory.getColumnsByName('"+o2m.getTargetEntity()+"'),store:storeFactory.getStoreByName('AM.store."+o2m.getTargetEntity()+"'),parentClass:'"+StringUtil.fristLetterLowerCase(form.getForm_name())+"'},");
			}else{*/
				//o2ms.append("{ xtype: 'fieldset', collapsible: true,collapsed:true,formBind : true,title:'"+o2m.getTitle()+"',sort:'"+o2m.getSort()+"',items:["+XtypeFactory.list(id, form.getForm_name(), o2m.getTargetEntity(),o2m.getName()).toString()+"]");
				o2ms.append("{  xtype: 'fieldcontainer',fieldLabel:'"+o2m.getTitle()+"',sort:'"+o2m.getSort()+"',items:["+xtypeManager.list(o2m.getTitle(),o2m.getName(), form.getForm_name(), o2m.getTargetEntity(),id).toString()+"]");
				
				/*if(subform!=null){
				for(O2O subo2o:subform.getO2os()){
					if(subo2o.isRenderToBuildForm())
					o2ms.append(",subsidiary:'"+subo2o.getTargetEntity()+"',relation='o2o'");
				}
				for(O2M subo2m:subform.getO2ms()){
					if(subo2m.isRenderToBuildForm())
					o2ms.append(",subsidiary:'"+subo2m.getTargetEntity()+"',relation='o2m'");
				}
				for(M2O subm2o:subform.getM2os()){
					if(subm2o.isRenderToBuildForm())
					o2ms.append(",subsidiary:'"+subm2o.getTargetEntity()+"',relation='m2o'");
					
				}
				}*/
				o2ms.append("},");
			o2ms.append("{");
			o2ms.append("xtype:'hiddenfield',name:'"+o2m.getName()+"'");
			o2ms.append("},");
			
			}
		}
o2m_list.append("]");
             StringUtil.deleteLastSymbol(o2ms, ",");
		/*if(o2ms.length()-1==o2ms.lastIndexOf(",")){
			o2ms.deleteCharAt(o2ms.length() - 1);
			
		}*/
		
		o2ms.append("],");
		System.out.println("Form:o2ms--------------------" + o2ms);
		result.append(prop).append(o2ms).append(o2m_list);
		//result.deleteCharAt(result.length() - 1);

		result.append("}");
		
		System.out.println("Form--------------------" + result);
		return result.toString();

	}
	

	public static String getColumn(Form form) {
		StringBuilder result = new StringBuilder();
		StringBuilder field = new StringBuilder();
		StringBuilder m2os = new StringBuilder();
		StringBuilder o2os = new StringBuilder();
		StringBuilder o2ms = new StringBuilder();
		
		XtypeManager target=new XtypeManagerIMP();
		InvocationHandler ds = new I18nProxy(target.getClass());
		XtypeManager xtypeManager=(XtypeManager) Proxy.newProxyInstance(XtypeManager.class.getClassLoader(), new Class[]{XtypeManager.class},ds);
		
	ButtonServiceManager buttonServiceManager=(ButtonServiceManager) ApplicationContextHelper.getBean("buttonServiceManagerIMP");
		
		LinkedHashMap<String,Object> bw=new LinkedHashMap<String,Object>();
		
		bw.put("targetName", StringUtil.fristLetterLowerCase(form.getForm_name()));
		bw.put("renderToActionColumn",true);
		List<Button> bs = null;
		try {
			 bs=buttonServiceManager.findList(bw, null, null,null);
		} catch (Exception e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		
		 
		result.append("[");
		for (KinColumn c : form.getKinColumns()) {
			System.out.println("xtype:"+c.getXtype());
			Xtype xtype=Xtype.valueOf(c.getXtype());
			field.append("{");
			field.append("header:'" + c.getHeader() + "',");
			field.append("sort:" + c.getSort() + ",");
			field.append("dataIndex:'" + c.getFieldName() + "'");
			if (c.isHidden()) {
				field.append(",hidden:true");
			}
			switch(xtype){
	        case combo:
	        	
				field.append(",editor:");
				
				field.append(xtypeManager.combo( null,c.getFieldName(),c.isAllowBlank(), c.getSort(), true, c.isEditor(), true, StringUtil.fristLetterUpperCase(c.getFieldName()),null, null, null, null));
			
				break;
	        	
	        case textfield:
	        	field.append(",editor:");
				field.append(xtypeManager.textfield(null,c.getFieldName(),c.getMinLength(),c.getMaxLength(),c.isAllowBlank(),c.getVtype(),0, c.isHidden()));
	        	
	        	break;
	        case numberfield:
	        	
				field.append(",editor:");
				
				field.append(xtypeManager.numberfield(null,c.getFieldName(),c.isAllowBlank(),c.getMin(),c.getMax(),c.getSort(), c.isHidden()));
			
	        	break;
	        	
	        case datefield:
	        	
			    field.append(",xtype: 'datecolumn'");
				field.append(", renderer:function(value){return value ? Ext.Date.dateFormat(value,'Y-m-d') : '';}");
				field.append(",editor:");
				
				field.append(xtypeManager.datefield(null,c.getFieldName(),c.isAllowBlank(),c.getSort(),"Y-m-d", c.isHidden(),true));
			break;
			
	        case checkbox:
	        	//field.append(",editor:");
	        	field.append(",xtype:'checkcolumn'");
	        	break;
				//field.append(XtypeFactory.checkbox(null));
           case ckeditorfield:
	        	
				field.append(",editor:");
			
				field.append(xtypeManager.ckeditorfield(null,c.getFieldName(),c.isAllowBlank(),c.getSort()));
			
	        	break;
	         }

				field.append("},");

		}
		
		
	
		
	
		try {
			 bs=buttonServiceManager.findList(bw, null, null,null);
			if(bs.size()>0){
				field.append("{align :'center',header:'操作',autoWidth:true,xtype:'actionbuttoncolumn',items:[");
				//field.append("{header:'操作',autoWidth:true, renderer: function(value, cellmeta, record) {var display='';display+='<input type=\"button\" class=\"add\" value=\"add\" src=\"extjs/resources/themes/images/spinner.gif\" alt=\"Add\" />';display+='<input type=\"button\" class=\"delete\" src=\"extjs/resources/themes/images/spinner.gif\" alt=\"Delete\"/>';return display;}");
				
			for(Button b:bs){
					field.append("{");
					field.append(" icon:'"+b.getIcon()+"', tooltip:'"+b.getLabel()+"',text:'"+b.getLabel()+"',action:'"+b.getAction()+"',cls:'"+b.getCls()+"',url:'"+b.getUrl()+"',targetName:'"+b.getTargetName()+"'");
					field.append("},");
					
			}
		    StringUtil.deleteLastSymbol(field, ",");
			
			field.append("]},");   
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		for(O2O o2o:form.getO2os()){
			if(o2o.isRenderToBuildForm()){
				if("authorize".equals(o2o.getName())){
				o2os.append("{");
				o2os.append("header:'" + o2o.getLabel() + "',");
				o2os.append("sort:" + o2o.getSort()+ ",");
				o2os.append("dataIndex:'" + o2o.getName() + "_id',");
				o2os.append("xtype:'actioncolumn'" +
						//",align:'center'" +
						",renderer: function (value, metadata, record) {"+
    "if (value!=null) {"+
						//"alert('no');"+
        "this.items[0].icon = 'images/extion.png';"+
        "this.items[0].disabled = true;"+
    "} else {"+
        //"alert('yes');"+
        "this.items[0].icon = 'images/best.png';"+
        "this.items[0].disabled = false;"+
    "}"+
"},");
				o2os.append("items:[{" +
						//"icon:'images/extion.png',"+
                          "tooltip: '鐢熸垚浜岀淮鐮?,"+
                          "style:'margin-left:5px',"+
							"getClass: function(value,metadata,record){"+
								"var closed = record.get('closed');"+
								  "if (closed == 0 ) {"+
									"return 'x-hide-display';"+
									"} else {"+
								  	"return 'x-grid-center-icon';"+
									"}"+
								
							"},"+
						"handler: function(grid, rowIndex, colIndex) {"+
						"var rec = grid.getStore().getAt(rowIndex);"+
						"var mc=(grid.getStore().getProxy().getModel().getName()).split('.')[2];"+
						"var m=Ext.util.Format.lowercase(Ext.util.Format.substr(mc,0, 1))+ Ext.util.Format.substr(mc, 1,mc.length- 1);"+
						"var me=this;"+
						"Ext.Ajax.request({"+
							"url : './authorize/add.action',"+
							"params : {"+
								"pid : rec.get(rec.idProperty),"+
							    "parentClass:m" +
							"},"+
							"async : false,"+
							"method : 'POST',"+
							"timeout : 3000,"+
							"success : function(response, opts) {"+
							//"alert((grid.getStore().getProxy().getModel().getName()).split('.')[2]);"+
							//"alert(rec.get(rec.idProperty));"+
							"grid.getStore().load();"+
							
					       // "this.items[0].disabled = true;"+
							"grid.refresh();"+
					       "grid.ownerCt.doLayout();"+
							"}"+
			             "});"+
                        
               "}}]");
              
				
				o2os.append("},");
				}
			}
		}
		
		for (M2O m : form.getM2os()) {
			
               if(m.isRenderToBuildForm()){
			m2os.append("{");
			m2os.append("header:'" + m.getLabel() + "',");
			m2os.append("sort:" + m.getSort()+ ",");
			m2os.append("dataIndex:'" + m.getName() + "_id" + "',");
			
			m2os.append("editor:"+xtypeManager.combo(null,m.getName(),m.isAllowBlank(),0,true,false,false,m.getTargetEntity(),m.getComboName(), null, null, null));
			m2os.append("},");
            	   }
		}
		
result.append(field).append(m2os).append(o2os);

result=StringUtil.deleteLastSymbol(result, ",");
		result.append("]");
		
		return result.toString();
	}
	
	
	

	
    
	

}
